package com.yilin.tms.data.controller;

import com.yilin.commons.util.ArrayUtil;
import com.yilin.commons.util.DateTimeUtil;
import com.yilin.commons.util.ZipUtil;
import com.yilin.tms.core.application.AppUtil;
import com.yilin.tms.core.application.PageData;
import com.yilin.tms.core.application.ReturnData;
import com.yilin.tms.core.commons.base.BaseController;
import com.yilin.tms.core.commons.annotation.NotNull;
import com.yilin.tms.core.commons.annotation.UserTarget;
import com.yilin.tms.core.commons.utils.ParamUtil;
import com.yilin.tms.core.components.minio.FileDealUtil;
import com.yilin.tms.core.components.minio.MinIoUploadResDTO;
import com.yilin.tms.core.entity.data.bill.BillOption;
import com.yilin.tms.core.entity.data.bill.TruckerBill;
import com.yilin.tms.core.entity.order.payment.OrderSettlementCost;
import com.yilin.tms.core.entity.order.transit.TransitOrder;
import com.yilin.tms.core.entity.user.UserType;
import com.yilin.tms.core.remote.IOrderRemote;
import com.yilin.tms.data.service.IBillService;
import com.yilin.tms.data.service.IMinOssService;
import com.yilin.tms.data.service.impl.MinOssService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 票据资料控制器
 * 代司机开票
 */
@RestController
@RequestMapping("/data/bill/")
public class BillController extends BaseController {
    @Value("${servlet.temporary-path}")
    String temporaryPath;
    
    @Resource
    IBillService truckerBillService;
    @Resource
    IOrderRemote orderRemote;
    @Resource
    private IMinOssService minOssService;

    /**
     * 查看票据生成列表
     * */
    @PostMapping("getTruckerBillPage")
    @NotNull({"page","limit"})
    @UserTarget({UserType.platformUser})
    public ReturnData<PageData<TruckerBill>> getTruckerBillPage(TruckerBill query, Integer page, Integer limit){
        PageData<TruckerBill> bills = truckerBillService.getTruckerBillPage(query,page,limit);
        return jsonView(true,"获取成功",bills);
    }

    /**
     * 新增司机开票票据
     * */
    @PostMapping("addTruckerBill")
    @NotNull({"involvedOrderIds"})
    @UserTarget({UserType.platformUser})
    public ReturnData<Object> addTruckerBill(TruckerBill truckerBill){
        if (truckerBill.getInvolvedOrderIds()==null) return jsonErrView("请选择运单");
        if (truckerBill.getInvolvedOrderIds().split(",").length==0) return jsonErrView("请选择运单");
        List<TransitOrder> transitOrderList = ParamUtil.isSuccess(orderRemote.getTransitOrderListByIds(truckerBill.getInvolvedOrderIds()));
        TransitOrder first = ArrayUtil.first(transitOrderList);
        for (TransitOrder transitOrder : transitOrderList) {
            if (!transitOrder.getRobOrganizeId().equals(first.getRobOrganizeId())) return jsonErrView("请选择相同车主进行开票");
        }
        List<OrderSettlementCost> settlementList = ParamUtil.isSuccess(orderRemote.getOrderSettlementListByTransOrderIds(truckerBill.getInvolvedOrderIds()));
        for (OrderSettlementCost cost : settlementList) {
            if (cost.getPayStatus() != OrderSettlementCost.PayStatus.success) return jsonErrView("存在运单未结算成功，无法创建票据");
        }
        truckerBill.setOrganizeId(first.getRobOrganizeId());
        truckerBill.setOrganizeName(first.getRobOrganizeName());
        truckerBill.setOrganizeAdminId(first.getRobAccountId());
        truckerBill.setOrganizeAdminName(first.getRobAccountName());
        truckerBillService.addTruckerBill(getLoginUser(),truckerBill,transitOrderList,settlementList);
        return jsonView(true,"保存成功");
    }

    /**
     * 作废票据
     * */
    @PostMapping("scrapTruckerBill")
    @NotNull({"truckerBillIds"})
    @UserTarget({UserType.platformUser})
    public ReturnData<Object> scrapTruckerBill(String[] truckerBillIds){
        List<TruckerBill> truckerBillList=truckerBillService.getTruckerBillsByIds(truckerBillIds);
        for (TruckerBill truckerBill : truckerBillList) {
            if (truckerBill.getBillStatus()== TruckerBill.BillStatus.complete){
                return jsonErrView("存在已完成的票据，请重新选择！");
            }
        }
        truckerBillService.scrapTruckerBill(getLoginUser(),truckerBillList);
        return jsonView(true,"操作成功");
    }

    /**
     * 下载并打包票据资料 票据更新为处理中
     * */
    @PostMapping("downloadTruckerBills")
    @NotNull({"truckerBillIds"})
    @UserTarget({UserType.platformUser})
    public ReturnData<Object> downloadTruckerBills(BillOption billOption,HttpServletResponse response)  {
        List<String> files = new ArrayList<>();
        String filePath = AppUtil.getTemporaryPath(temporaryPath)+"\\bills\\";
        if (!new File(filePath).exists()) new File(filePath).mkdir();
        String dateString = DateTimeUtil.dateToString(new Date(),"yyyy-MM-dd");
        List<TruckerBill> truckerBillList=truckerBillService.getTruckerBillsByIds(billOption.getTruckerBillIds());
        for (TruckerBill truckerBill : truckerBillList) {
            files.add(truckerBillService.generatePdf(getLoginUser(),filePath, truckerBill, billOption));
        }
        String pdfPath = String.format("%s开票存档资料 %s.zip",filePath,dateString);
        ZipUtil.compressFilesZip(files,pdfPath,"");
        String excelPath = truckerBillService.generateExcel(getLoginUser(),filePath, truckerBillList);
        //生成最终打包下载地址
        String finalZipPath = String.format("%s开票资料%s.zip",filePath,dateString);
        ZipUtil.compressFilesZip(ArrayUtil.initList(pdfPath,excelPath),finalZipPath,"");
        //上传到临时文件夹
        MultipartFile multipartFile = FileDealUtil.getMultipartFile(new File(finalZipPath));
        MinIoUploadResDTO upload = minOssService.upload(multipartFile, MinOssService.UploadType.temp.path, "bill");
        System.out.println("路径生成成功，返回前端即可下载："+upload.getMinFileUrl());
        //上传成功后，删除临时打包文件夹
        //FileDealUtil.deleteFile(new File(filePath));
        return jsonView(true,"临时路径生成成功，请尽快下载！",upload.getMinFileUrl());
    }

    /**
     * 处理票据 标记为完成
     * */
    @PostMapping("dealTruckerBills")
    @NotNull({"truckerBillIds"})
    @UserTarget({UserType.platformUser})
    public ReturnData<Object> dealTruckerBills(String[] truckerBillIds){

        return jsonView(true,"处理成功");
    }

    //-------------

    /**
     * 下载并打包司机资料
     * */
    @PostMapping("generateTruckerPdf")
    @NotNull({"accountIds"})
    @UserTarget({UserType.platformUser})
    public ReturnData<Object> generateTruckerPdf(String[] accountIds)  {
        List<String> files = new ArrayList<>();
        String filePath = AppUtil.getTemporaryPath(temporaryPath)+"\\bills\\";
        if (!new File(filePath).exists()) new File(filePath).mkdir();
        String dateString = DateTimeUtil.dateToString(new Date(),"yyyy-MM-dd");

        files.add(truckerBillService.generateTruckerPdf(getLoginUser(),filePath, accountIds));
        String pdfPath = String.format("%s开票存档资料 %s.zip",filePath,dateString);
        ZipUtil.compressFilesZip(files,pdfPath,"");
        //生成最终打包下载地址
//        String finalZipPath = String.format("%s开票资料%s.zip",filePath,dateString);
//        ZipUtil.compressFilesZip(ArrayUtil.initList(pdfPath,excelPath),finalZipPath,"");
        //上传到临时文件夹
        MultipartFile multipartFile = FileDealUtil.getMultipartFile(new File(pdfPath));
        MinIoUploadResDTO upload = minOssService.upload(multipartFile, MinOssService.UploadType.temp.path, "bill");
        System.out.println("路径生成成功，返回前端即可下载："+upload.getMinFileUrl());
        //上传成功后，删除临时打包文件夹
        FileDealUtil.deleteFile(new File(filePath));
        return jsonView(true,"临时路径生成成功，请尽快下载！",upload.getMinFileUrl());
    }

    /**
     * 下载并打包车辆信息单
     * */
    @PostMapping("generateVehiclePdf")
    @NotNull({"vehicleIds"})
    @UserTarget({UserType.platformUser})
    public ReturnData<Object> generateVehiclePdf(String[] vehicleIds)  {
        List<String> files = new ArrayList<>();
        String filePath = AppUtil.getTemporaryPath(temporaryPath)+"\\bills\\";
        if (!new File(filePath).exists()) new File(filePath).mkdir();
        String dateString = DateTimeUtil.dateToString(new Date(),"yyyy-MM-dd");

        files.add(truckerBillService.generateVehiclePdf(getLoginUser(),filePath, vehicleIds));
        String pdfPath = String.format("%s开票存档资料 %s.zip",filePath,dateString);
        ZipUtil.compressFilesZip(files,pdfPath,"");
        //生成最终打包下载地址
        //上传到临时文件夹
        MultipartFile multipartFile = FileDealUtil.getMultipartFile(new File(pdfPath));
        MinIoUploadResDTO upload = minOssService.upload(multipartFile, MinOssService.UploadType.temp.path, "bill");
        System.out.println("路径生成成功，返回前端即可下载："+upload.getMinFileUrl());
        //上传成功后，删除临时打包文件夹
        FileDealUtil.deleteFile(new File(filePath));
        return jsonView(true,"临时路径生成成功，请尽快下载！",upload.getMinFileUrl());
    }

    /**
     * 下载并打包运单信息列表 + 合同
     * */
    @PostMapping("generateTransitOrderPdf")
    @NotNull({"transitOrderIds"})
    @UserTarget({UserType.platformUser})
    public ReturnData<Object> generateTransitOrderPdf(String[] transitOrderIds)  {
        List<String> files = new ArrayList<>();
        String filePath = AppUtil.getTemporaryPath(temporaryPath)+"\\bills\\";
        if (!new File(filePath).exists()) new File(filePath).mkdir();
        String dateString = DateTimeUtil.dateToString(new Date(),"yyyy-MM-dd");

        files.add(truckerBillService.generateTransitOrderPdf(getLoginUser(),filePath, transitOrderIds));
        String pdfPath = String.format("%s开票存档资料 %s.zip",filePath,dateString);
        ZipUtil.compressFilesZip(files,pdfPath,"");
        //生成最终打包下载地址
        //上传到临时文件夹
        MultipartFile multipartFile = FileDealUtil.getMultipartFile(new File(pdfPath));
        MinIoUploadResDTO upload = minOssService.upload(multipartFile, MinOssService.UploadType.temp.path, "bill");
        System.out.println("路径生成成功，返回前端即可下载："+upload.getMinFileUrl());
        //上传成功后，删除临时打包文件夹
        FileDealUtil.deleteFile(new File(filePath));
        return jsonView(true,"临时路径生成成功，请尽快下载！",upload.getMinFileUrl());
    }

    /**
     * 下载并打包结算信息单
     * */
    @PostMapping("generateSettlementOrderPdf")
    @NotNull({"settlementCostIds"})
    @UserTarget({UserType.platformUser})
    public ReturnData<Object> generateSettlementOrderPdf(String[] settlementCostIds)  {
        List<String> files = new ArrayList<>();
        String filePath = AppUtil.getTemporaryPath(temporaryPath)+"\\bills\\";
        if (!new File(filePath).exists()) new File(filePath).mkdir();
        String dateString = DateTimeUtil.dateToString(new Date(),"yyyy-MM-dd");

        files.add(truckerBillService.generateSettlementOrderPdf(getLoginUser(),filePath, settlementCostIds));
        String pdfPath = String.format("%s开票存档资料 %s.zip",filePath,dateString);
        ZipUtil.compressFilesZip(files,pdfPath,"");
        //生成最终打包下载地址
        //上传到临时文件夹
        MultipartFile multipartFile = FileDealUtil.getMultipartFile(new File(pdfPath));
        MinIoUploadResDTO upload = minOssService.upload(multipartFile, MinOssService.UploadType.temp.path, "bill");
        System.out.println("路径生成成功，返回前端即可下载："+upload.getMinFileUrl());
        //上传成功后，删除临时打包文件夹
        FileDealUtil.deleteFile(new File(filePath));
        return jsonView(true,"临时路径生成成功，请尽快下载！",upload.getMinFileUrl());
    }

    /**
     * 下载并打包回单信息单
     * */
    @PostMapping("generateReceiptOrderPdf")
    @NotNull({"transitOrderNoteIds"})
    @UserTarget({UserType.platformUser})
    public ReturnData<Object> generateReceiptOrderPdf(String[] transitOrderNoteIds)  {
        List<String> files = new ArrayList<>();
        String filePath = AppUtil.getTemporaryPath(temporaryPath)+"\\bills\\";
        if (!new File(filePath).exists()) new File(filePath).mkdir();
        String dateString = DateTimeUtil.dateToString(new Date(),"yyyy-MM-dd");

        files.add(truckerBillService.generateReceiptOrderPdf(getLoginUser(),filePath, transitOrderNoteIds));
        String pdfPath = String.format("%s开票存档资料 %s.zip",filePath,dateString);
        ZipUtil.compressFilesZip(files,pdfPath,"");
        //生成最终打包下载地址
        //上传到临时文件夹
        MultipartFile multipartFile = FileDealUtil.getMultipartFile(new File(pdfPath));
        MinIoUploadResDTO upload = minOssService.upload(multipartFile, MinOssService.UploadType.temp.path, "bill");
        System.out.println("路径生成成功，返回前端即可下载："+upload.getMinFileUrl());
        //上传成功后，删除临时打包文件夹
        FileDealUtil.deleteFile(new File(filePath));
        return jsonView(true,"临时路径生成成功，请尽快下载！",upload.getMinFileUrl());
    }

}
